# coding: utf-8
# Author: zhenda

import logging
import logging.handlers
from flask import request
import os


class RequestShoppingFormatter(logging.Formatter):
    """
    自定义的日志输出格式
    """

    def format(self, record):
        record.url = request.url  # 记录请求地址
        record.remote_addr = request.remote_addr  # 记录客户端地址
        return super().format(record)


# 创建logger对象
def create_logger(app):
    """
    设置日志的配置
    :param app:
    :return:
    """
    logging_level = app.config['LOGGING_LEVEL']
    logging_file_dir = app.config['LOGGING_FILE_DIR']
    logging_file_max_bytes = app.config['LOGGING_FILE_MAX_BYTES']
    logging_file_backup = app.config['LOGGING_FILE_BACKUP']

    # 1. 设置输出格式(针对文件)
    request_formatter = RequestShoppingFormatter('[%(asctime)s] %(remote_addr)s 请求 %(url)s \t %(levelname)s '
                                                 '在 %(module)s %(lineno)d : %(message)s')
    if not os.path.isdir(logging_file_dir):
        os.mkdir(logging_file_dir)
    # 2. 自定义目录和日志文件
    flask_file_handler = logging.handlers.RotatingFileHandler(filename=os.path.join(logging_file_dir, 'shopping.log'),
                                                              maxBytes=logging_file_max_bytes,
                                                              backupCount=logging_file_backup, encoding='utf-8')
    # 给当前handler设置格式
    flask_file_handler.setFormatter(request_formatter)
    # 3. 得到logger对象
    flask_logger = logging.getLogger('Shopping')  # 起一个名字
    flask_logger.addHandler(flask_file_handler)
    flask_logger.setLevel(logging_level)

    # 整个项目需要两个handler ：文件日志， 控制台日志
    flask_console_handler = logging.StreamHandler()
    flask_console_handler.setFormatter(logging.Formatter('[%(asctime)s] %(levelname)s 在 %(module)s %(lineno)d : '
                                                         '%(message)s'))

    # 当项目为debug模式，也使用控制台输出日志
    if app.debug:
        flask_logger.addHandler(flask_console_handler)
